#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
#include <string.h>
 #include <semaphore.h>

int num = 0;
pthread_mutex_t mutex;
//pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
//线程函数
//int pthread_create(pthread_t *thread, const pthread_attr_t *attr,void *(*start_routine) (void *), void *arg);
void *threadFun(void *arg)
{
    //上锁
    pthread_mutex_lock(&mutex);
    int i = 1000000;
    
    while(i--)
    {
        num++;
    }
    pthread_mutex_unlock(&mutex);
}
 
int main()
{
    //初始化一个线程互斥锁

    pthread_mutex_init(&mutex,NULL);
    
    pthread_t tid1;
    pthread_t tid2;
    //创建线程
    pthread_create(&tid1,NULL,threadFun,NULL);
    pthread_create(&tid2,NULL,threadFun,NULL);
    //创建信号量，实现PV操作
    pthread_join(tid1,NULL);
    pthread_join(tid2,NULL);
    printf("in main thread ID = %ld\n",tid1);
    printf("in main thread ID = %ld\n",tid2);

    printf("num = %d\n",num);

    //销毁互斥锁对象
    pthread_mutex_destroy(&mutex);

    return 0;
}